# -*- coding: utf-8 -*-
import hashlib
import datetime

from django.db import models
from django.utils import timezone


class BkMiniWeixinUserManager(models.Manager):
    def create_user(self, openid, **extra_fields):
        now = timezone.now()
        if not openid:
            raise ValueError('The given openid must be set')
        user = self.model(openid=openid, date_joined=now, **extra_fields)
        user.save()
        return user

    def get_update_or_create_user(self, openid, **extra_fields):
        """
        获取用户，无则创建，有则更新
        """
        try:
            user = self.get(openid=openid)
            update_fields = ['nickname', 'gender', 'country', 'city', 'province', 'avatar_url']
            for field in update_fields:
                field_value = extra_fields.get(field) or ''
                if field_value:
                    setattr(user, field, field_value)
            user.save()
        except self.model.DoesNotExist:
            user = self.create_user(openid, **extra_fields)
        return user


class BkMiniWeixinUser(models.Model):
    """微信公众号用户"""
    openid = models.CharField(u"微信用户应用唯一标识", max_length=128, unique=True)
    nickname = models.CharField(u"昵称", max_length=127, blank=True)
    gender = models.CharField(u"性别", max_length=15, blank=True)
    country = models.CharField(u"国家", max_length=63, blank=True)
    province = models.CharField(u"省份", max_length=63, blank=True)
    city = models.CharField(u"城市", max_length=63, blank=True)
    avatar_url = models.CharField(u"头像", max_length=255, blank=True)
    date_joined = models.DateTimeField(u"加入时间", default=timezone.now)

    class Meta:
        db_table = 'bk_mini_weixin_user'
        verbose_name = u"微信小程序用户"
        verbose_name_plural = u"微信小程序用户"

    objects = BkMiniWeixinUserManager()

    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True


class BkMiniWeiXinUserSessionManager(models.Manager):
    def create_user_session(self, openid, session_key):
        """
        根据openid和微信登录后获取的对应会话密钥session_key生成会话
        """
        bktoken = hashlib.sha256(session_key).hexdigest()
        # 清除之前的登录态
        self.filter(openid=openid).delete()
        session = self.model(openid=openid, bktoken=bktoken, session_key=session_key,
                             expires_date=timezone.now() + datetime.timedelta(days=30))
        session.save()
        return session.bktoken


class BkMiniWeiXinUserSession(models.Model):
    openid = models.CharField(u"微信用户应用唯一标识", max_length=255, unique=True)
    session_key = models.CharField(u"微信登录后获取的对应会话密钥", max_length=255)
    bktoken = models.CharField(u"登录生成的Token", max_length=255, unique=True)
    expires_date = models.DateTimeField(u"失效时间")

    class Meta:
        db_table = 'bk_mini_weixin_user_session'
        verbose_name = u"微信小程序用户Session"
        verbose_name_plural = u"微信小程序用户Session"

    objects = BkMiniWeiXinUserSessionManager()
